package com.xys.zxinglib;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;

import com.xys.libzxing.zxing.encoding.EncodingUtils;

import java.io.File;
import java.io.IOException;
import java.util.logging.LogRecord;

public class MainActivity extends Activity {

    private static String URL_CHUXING = "https://qr.ekuaitu.com/app/qrcode.html?bike=";
    private static String URL_TRAVEL = "https://qr.ekuaitu.com/travel/qrcode.html?bike=";
    private static String urlPrefix = "";
    private static String dirName = "";
    private Context context = this;
    private TextView textView_progress;
    private EditText editText_start;
    private TextView text_end;
    private EditText editText_count;
    private Button button_start;
    private RadioGroup radioGroup;
    private RadioButton button_chuxing;
    private RadioButton button_travel;
    private Button button_cancel;
    private Thread mThread;
    private Runnable mRunnable;
    private int startNum;
    private int endNum;
    private String path;
    private ProgressDialog progressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
        textView_progress = (TextView) findViewById(R.id.textView_progress);
        editText_start = (EditText) findViewById(R.id.editText_start);
        text_end = (TextView) findViewById(R.id.text_end);
        editText_count = (EditText) findViewById(R.id.editText_count);
        button_start = (Button) findViewById(R.id.button_start);
        button_travel = (RadioButton) findViewById(R.id.button_travel);
        button_chuxing = (RadioButton) findViewById(R.id.button_chuxing);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == button_chuxing.getId()) {
                    urlPrefix = URL_CHUXING;
                    dirName = "KuaituChuxingQR";
                    path = SDCardUtils.getSDCardPath() + dirName + File.separator;
                } else if (i == button_travel.getId()) {
                    urlPrefix = URL_TRAVEL;
                    dirName = "KuaituTravelQR";
                    path = SDCardUtils.getSDCardPath() + dirName + File.separator;
                }
            }
        });

        button_start.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (editText_start.getText().toString().trim().equals("") || editText_count.getText().toString().trim().equals("")) {
                    Toast.makeText(context, "请输入编号", Toast.LENGTH_LONG).show();
                    return;
                }
                startNum = Integer.parseInt(editText_start.getText().toString().trim());
                endNum = Integer.parseInt(editText_count.getText().toString().trim()) + startNum-1;

                if (startNum <= 0 || endNum <= 0) {
                    Toast.makeText(context, "请输入正确的编号", Toast.LENGTH_LONG).show();
                    return;
                }
                if (startNum > endNum) {
                    Toast.makeText(context, "结束编号必须大于开始编号", Toast.LENGTH_LONG).show();
                    return;
                }
                if (endNum > 100000000) {
                    Toast.makeText(context, "结束编号太大了", Toast.LENGTH_LONG).show();
                    return;
                }
                if (urlPrefix.equals("")) {
                    Toast.makeText(context, "请选择前缀", Toast.LENGTH_LONG).show();
                    return;
                }
                progressDialog = new ProgressDialog(context);
                progressDialog.setCancelable(false);
                mRunnable = new MyRunnable();
                mThread = new Thread(mRunnable);
                mThread.start();
            }
        });

        final TextWatcher startWatch = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().equals("") || charSequence.toString().equals("-")) {
                    charSequence = "0";
                }
                if (!editText_count.getText().toString().trim().equals("")) {
                    text_end.setText(Integer.parseInt(charSequence.toString().trim()) + Integer.parseInt(editText_count.getText().toString().trim())-1 + "");
                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };


        final TextWatcher countWatch = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().equals("") || charSequence.toString().equals("-")) {
                    charSequence = "0";
                }
                if (!editText_start.getText().toString().trim().equals("")) {
                    text_end.setText(Integer.parseInt(editText_start.getText().toString().trim()) + Integer.parseInt(charSequence.toString().trim())-1 + "");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };

        editText_start.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                editText_start.addTextChangedListener(startWatch);
            }
        });


        editText_count.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                editText_count.addTextChangedListener(countWatch);
            }
        });

    }

    private class MyRunnable implements Runnable {
        @Override
        public void run() {
            Message message = new Message();
            message.arg1 = 1;
            handler.sendMessage(message);
            FileUtils.deleteDir(path);
            int count = endNum - startNum;
            for (int i = startNum; i <= endNum; i++) {
                Message message2 = new Message();
                message2.arg1 = 2;
                message2.arg2 = (int) ((i - startNum) / (float) count * 100);
                handler.sendMessage(message2);
                //根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小（600, 600）
                Bitmap qrCodeBitmap = EncodingUtils.createQRCode(urlPrefix + i, 600, 600, null);
                ImageUtils.save(qrCodeBitmap, path + i + ".png", Bitmap.CompressFormat.PNG, true);
            }
            Message message3 = new Message();
            message3.arg1 = 3;
            handler.sendMessage(message3);
            try {
                boolean zipResult = ZipUtils.zipFile(path, SDCardUtils.getSDCardPath() + File.separator + dirName + ".zip");
                Message message4 = new Message();
                if (zipResult) {
                    message4.arg1 = 5;
                } else {
                    message4.arg1 = 6;
                }
                handler.sendMessage(message4);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 1://删除目录
                    progressDialog.setMessage("正在删除旧文件...");
                    progressDialog.show();
                    break;
                case 2://生成中
                    progressDialog.setMessage(msg.arg2 + "%");
                    break;
                case 3://压缩中
                    progressDialog.setMessage("正在压缩...");
                    break;
                case 4://删除完毕
                    textView_progress.setText("已取消");
                    break;
                case 5://完成
                    progressDialog.dismiss();
                    textView_progress.setText("已完成，请到根目录下找到“" + dirName + ".zip”文件");
                    break;
                case 6://压缩中失败
                    progressDialog.setMessage("压缩失败,请重试");
                    textView_progress.setText("压缩失败,请重试");
                    break;
            }
        }
    };
}